import { Sprite, SpriteFrame } from "cc";
import { BaseComponent, Maths, _config_, _resouces, _timer, ccclass } from "../../main/script/Main";


@ccclass("Item")
export class Item extends BaseComponent {

    private cSprite_icon: Sprite = null!

    public _isScaleAnim: boolean = false
    private _isScaleAnimVisible: boolean = false
    private _isScaleAnimOnce: boolean = false
    private _isScaleAnimX: boolean = false
    private _dtNum: number = 0
    private _duration = 0
    private _complete: () => void = null!

    private _initScaleX = -1

    onLoad(): void {
        super.onLoad()
        this._initScaleX = this.node.scale.x
    }

    public setConfigFrame(configId: number) {
        let _config = _config_.obj.card_item[configId]
        this.cSprite_icon.spriteFrame = _resouces.get(_config.icon_url, SpriteFrame)
    }

    public hasVisible() {
        return this.SwitchSpriteCC.index == 0
    }

    public setIconState(value: boolean) {
        this.SwitchSpriteCC.index = value ? 0 : 1
        this.cSprite_icon.node.active = value
    }

    protected onUpdate(): void {
        if (this._isScaleAnim) {
            this._dtNum += _timer.dt

            let animationRatio = this._dtNum / this._duration
            if (animationRatio >= 1) {
                animationRatio = 1
                if (!this._isScaleAnimOnce) {
                    this._isScaleAnim = false
                    if (this._complete)
                        this.scheduleOnce(this._complete)
                    this._complete = null!
                }

                if (this._isScaleAnimOnce) {
                    this._dtNum = 0
                    animationRatio = 0
                    this._isScaleAnimOnce = false
                    this.setIconState(this._isScaleAnimVisible)
                }
            }
            let scale = (!this._isScaleAnimOnce ? animationRatio : (1 - animationRatio)) * this._initScaleX
            if (this._isScaleAnimX)
                this.setScaleX(scale, false)
            else
                this.setScaleY(scale, false)
        }
    }

    public scaleAnim(_duration: number, _complete?: () => void, _isVisible = true, _randomScaleX: "random" | "x" | "y" = "random") {
        if (_duration == 0) {
            this._isScaleAnim = false
            this.setScaleX(this._initScaleX, false)
            this.setScaleY(this._initScaleX, false)
            this.setIconState(_isVisible)
            if (_complete)
                _complete()
            return
        }

        this._isScaleAnim = true
        this._isScaleAnimOnce = true
        this._isScaleAnimVisible = _isVisible
        if (_randomScaleX == "random") {
            this._isScaleAnimX = Maths.isRandom(0.5)
        } else {
            this._isScaleAnimX = _randomScaleX == "x"
        }
        this._dtNum = 0
        this._duration = _duration / 2
        this._complete = _complete
        this.setIconState(!this._isScaleAnimVisible)
    }

}